#include <fasys/channels_manager.hpp>
#include <fasys/subscriber_manager.hpp>
#include <fasys/isubscriber.hpp>
#include <fasys/isubscriptions.hpp>
#include <fasys/cservice/cservice.hpp>
#include <fas/mux/best_mux.hpp>

using namespace fasys;

class test_receiver
  : public isubscriber
{

  isubscriptions* _source;
  std::string _key;
  std::string _uuid;
public:

  test_receiver(const std::string& key, isubscriptions* source)
    : _source(source), _key(key)
  {
  }

  void create_subscription()
  {
    subscriber_manager::channel_list channel_list;
    subscription_channel cs;
    cs.channel = "channel1";
    cs.min_size = 1;
    cs.max_size = 1;
    channel_list.push_back(cs);
    _uuid = _source->create(_key, 3600, channel_list);
    std::cout << _uuid << std::endl;
  }

  void subscribe()
  {
    std::list<message> ml;
    _source->move_messages(_key, _uuid, ml);
    if ( ml.empty() )
      _source->subscribe(_key,  _uuid, this);
    else
    {
      std::list<message>::iterator itr = ml.begin();
      for ( ;itr!=ml.end(); ++itr )
        _show(*itr);
    }
  }

  virtual void published(const message& m)
  {
    _show(m);
    _source->describe(_key, _uuid, this);
  }
  
  void _show(const message& m)
  {
    std::cout << "YO!!!!!!!!!!!!!!!!!!!!!" << std::endl;
    std::cout << m.channel << " " << m.channel_id << " " << m.message_id<< std::endl;
    std::cout << m.str() << std::endl;
  }
};

int main()
{
  subscriber_manager sm;
  channels_manager cm;
  sm.set_channels(&cm);
  test_receiver receiver("", &sm);
  receiver.create_subscription();
  receiver.subscribe();
  
  /*
  subscriber_manager::channel_list channel_list;
  subscription_channel cs;
  cs.channel = "channel1";
  cs.min_size = 1;
  cs.max_size = 1;
  channel_list.push_back(cs);
  std::string uuid = sm.create(3600, channel_list);
  

  test_receiver receiver(&sm);
  sm.subscribe( uuid, &receiver);
  */
  
  //
  message m;
  m.create("channel1", 10, 3600, 0);
  m.str("content1");
  cm.publish(m);
  m.create("channel1", 10, 3600, 0);
  m.str("content2");
  cm.publish(m);
  m.create("channel1", 10, 3600, 0);
  m.str("content3");
  cm.publish(m);
  receiver.subscribe();
  m.create("channel1", 10, 3600, 0);
  m.str("content4");
  cm.publish(m);
  receiver.subscribe();
  receiver.subscribe();
  m.create("channel1", 10, 3600, 0);
  m.str("content5");
  cm.publish(m);
  receiver.subscribe();

  
  /***
  {"jsonrpc": "2.0", "method": "publish", "params": {"channel":"channel1", "content":"content6"}}
  */

  cservice::cservice channel_service;
  channel_service.initialize(&cm);
  ::fas::mux::best_mux mux;
  channel_service.start(&mux, cservice::config() );
  for (;;)
    mux.select(-1);

  return 0;
}